import requests
from lxml import etree
import re

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',
}


# 主页面板
def main_weather(tree):
    mainWeather = {}
    # 更新时间
    updateTime = tree.xpath('/html/body/div[3]/div[3]/div/div[1]/div/div/p/text()')[0]
    mainWeather.update({'updateTime': f'{updateTime}'})
    # 气温图片
    now_img = tree.xpath('/html/body/div[3]/div[3]/div/div[1]/div/div/div[1]/div[1]/img/@src')[0]
    mainWeather.update({'now_img': f'{now_img}'})
    # 现在气温
    now_tmp = tree.xpath('/html/body/div[3]/div[3]/div/div[1]/div/div/div[1]/div[2]/p[1]/text()')[0]
    mainWeather.update({'now_tmp': f'{now_tmp}'})
    # 现在天气状态
    now_state = tree.xpath('/html/body/div[3]/div[3]/div/div[1]/div/div/div[1]/div[2]/p[2]/text()')[0]
    mainWeather.update({'now_state': f'{now_state}'})
    # 现在天气叙述
    now_text = tree.xpath('/html/body/div[3]/div[3]/div/div[1]/div/div/div[2]/text()')[0]
    now_text = now_text.replace("\n", '').replace(' ', '')
    mainWeather.update({'now_text': f'{now_text}'})
    # 风向
    now_windDir = tree.xpath('/html/body/div[3]/div[3]/div/div[1]/div/div/div[3]/div[1]/p[2]/text()')[0]
    mainWeather.update({'now_windDir': f'{now_windDir}'})
    # 风力
    now_windPower = tree.xpath('/html/body/div[3]/div[3]/div/div[1]/div/div/div[3]/div[1]/p[1]/text()')[0]
    now_windPower = now_windPower.replace("\n", '').replace(' ', '')
    mainWeather.update({'now_windPower': f'{now_windPower}'})
    # 相对湿度
    now_humidity = tree.xpath('/html/body/div[3]/div[3]/div/div[1]/div/div/div[3]/div[2]/p[1]/text()')[0]
    mainWeather.update({'now_humidity': f'{now_humidity}'})
    # 紫外线
    now_ultraviolet = tree.xpath('/html/body/div[3]/div[3]/div/div[1]/div/div/div[3]/div[3]/p[1]/text()')[0]
    mainWeather.update({'now_ultraviolet': f'{now_ultraviolet}'})
    # 体感温度
    now_bodytmp = tree.xpath('/html/body/div[3]/div[3]/div/div[1]/div/div/div[3]/div[4]/p[1]/text()')[0]
    mainWeather.update({'now_bodytmp': f'{now_bodytmp}'})
    # 能见度
    now_see = tree.xpath('/html/body/div[3]/div[3]/div/div[1]/div/div/div[3]/div[5]/p[1]/text()')[0]
    mainWeather.update({'now_see': f'{now_see}'})
    # 大气压
    now_atmos = tree.xpath('/html/body/div[3]/div[3]/div/div[1]/div/div/div[3]/div[7]/p[1]/text()')[0]
    mainWeather.update({'now_atmos': f'{now_atmos}'})

    # print(mainWeather)
    return mainWeather


# 未来7天天气预报
# 包含（周几，日期，最高/低温）
def weather_day7(tree):
    day7 = []
    for i in range(7):
        # 周几
        date = tree.xpath(
            f'/html/body/div[3]/div[3]/div/div[3]/div[1]/div[6]/div/div[1]/a[{i + 1}]/div[1]/div/p[1]/text()')[0]
        # 日期
        datetime = tree.xpath(
            f'/html/body/div[3]/div[3]/div/div[3]/div[1]/div[6]/div/div[1]/a[{i + 1}]/div[1]/div/p[2]/text()')[0]
        # 最低温
        minTemp = tree.xpath(
            f'/html/body/div[3]/div[3]/div/div[3]/div[1]/div[6]/div/div[1]/a[{i + 1}]/div[2]/div[2]/span[2]/text()')[0]
        # 最高温
        maxTemp = tree.xpath(
            f'/html/body/div[3]/div[3]/div/div[3]/div[1]/div[6]/div/div[1]/a[{i + 1}]/div[2]/div[2]/span[1]/text()')[0]
        # 图片
        src = tree.xpath(
            f'/html/body/div[3]/div[3]/div/div[3]/div[1]/div[6]/div/div[1]/a[{i + 1}]/div[1]/img/@src')[0]
        day7.append({
            'date': date,
            'datetime': datetime,
            'minTemp': minTemp,
            'maxTemp': maxTemp,
            'src': src
        })
    # print(day7)
    return day7


# 生活指数
def weather_indices(tree):
    indices = []
    for i in range(8):
        # 周几
        title = tree.xpath(
            f'/html/body/div[3]/div[3]/div/div[3]/div[1]/div[13]/div/div/div[{i + 1}]/a/div[2]/h4/text()')[0]
        level = tree.xpath(
            f'/html/body/div[3]/div[3]/div/div[3]/div[1]/div[13]/div/div/div[{i + 1}]/a/div[2]/h5/text()')[0]
        indices.append({
            'title': title,
            'level': level
        })
    # print(indices)
    return indices


# 空气质量
def weather_air(text):
    tree = etree.HTML(text)
    word = tree.xpath('/html/body/div[3]/div[3]/div/div[3]/div[1]/div[9]/div/div[1]/div[1]/p/text()')[0]
    air = re.findall('window.air = (.*?);', text)[0]
    aqi = re.findall('"aqi":(.*?),', air)[0]
    pm25 = re.findall('"pm25":(.*?),', air)[0]
    pm10 = re.findall('"pm10":(.*?),', air)[0]
    so2 = re.findall('"so2":(.*?),', air)[0]
    co = re.findall('"co":(.*?),', air)[0]
    o3 = re.findall('"o3":(.*?),', air)[0]
    no2 = re.findall('"no2":(.*?)}', air)[0]
    data = {
        'word': word,
        'aqi': aqi,
        'pm25': pm25,
        'pm10': pm10,
        'so2': so2,
        'co': co,
        'o3': o3,
        'no2': no2
    }
    # print(air)
    # print(data)
    return data


# 未来24小时
def weather_hou24(text):
    hour24 = re.findall('window.hour24 = (.*?);', text)[0]
    data = re.findall('{"time":"(.*?)","code":"(.*?)","tmp":"(.*?)","deg":(.*?)}', hour24)
    List = []
    for i in range(len(data)):
        obj = {
            'time': data[i][0],
            'code': data[i][1],
            'tmp': data[i][2],
            'deg': data[i][3],
        }
        List.append(obj)
    return List


# 主页数据
def mainHtml(city, code):
    weather_url = f'https://www.qweather.com/weather/{city}-{str(code)}.html'
    try:
        response = requests.get(url=weather_url, headers=headers)
        weather_tree = etree.HTML(response.text)

        hour24 = weather_hou24(response.text)
        air = weather_air(response.text)
        main = main_weather(weather_tree)
        day7 = weather_day7(weather_tree)
        indices = weather_indices(weather_tree)
        
        data = {
            'main': main,
            'hour24': hour24,
            'day7': day7,
            'air': air,
            'indices': indices
        }
        # print(data)
        return data
    except:
        string = '爬取失敗,请检查输入的参数是否正确'
        print(string)
        return string


# 测试代码
mainHtml('guangzhou', 101280101)